package com.swang.pms.web.listener;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.swang.pms.model.constants.CommonConstants;
import com.swang.pms.model.entity.ManageUser;

/**
 * @ClassName: SessionListener
 * @Description: TODO
 * @author 王泽
 * @date 2017年3月16日 下午9:45:51
 */
public class SessionListener implements HttpSessionListener {

    private static Logger                   logger      = Logger.getLogger(SessionListener.class);

    private static Map<String, HttpSession> ONLINE_USER = new ConcurrentHashMap<String, HttpSession>();

    @Override
    public void sessionCreated(HttpSessionEvent session) {
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        Object admin = se.getSession().getAttribute(CommonConstants.SESSION_USER_KEY);
        if (admin != null && admin instanceof ManageUser) {
            ONLINE_USER.remove(((ManageUser) admin).getMngId());
        }
    }

    public static void addSessionUser(String id, HttpSession session) {
        if (session != null && !StringUtils.isEmpty(id) && session.getAttribute(CommonConstants.KAPTCHA_SESSION_KEY) != null) {
            if (ONLINE_USER.get(id) != null) {
                try {
                    ONLINE_USER.get(id).invalidate();
                } catch (IllegalStateException e) {
                    logger.error("invalidate error !", e);
                }
            }
            ONLINE_USER.put(id, session);
        }
    }
}
